package com.blog.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.Utils.Result;
import com.blog.bean.domain.CourseClass;
import com.blog.bean.dto.CourseClassDTO;
import com.blog.bean.vo.CourseClassVO;
import com.blog.mapper.CourseClassMapper;
import com.blog.service.CourseClassService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 任浩
 * @version 1.0
 */

@Slf4j
@Service
public class CourseClassServiceImpl implements CourseClassService {

    @Autowired
    private CourseClassMapper courseClassMapper;

    /**
     * 新增课程类别
     * @param courseClass
     * @return
     */
    @Transactional
    @Override
    public Result add(CourseClassDTO courseClass) {
        if(courseClass == null || courseClass.getName() == null || "".equals(courseClass.getName())){
            log.info("课程类别名称不能为空");
            return Result.error("课程类别名称不能为空");
        }

        CourseClass data = new CourseClass();
        data.setName(courseClass.getName());
        if(courseClass.getParent() == null){
            data.setParent(0);
        }
        else {
            data.setParent(courseClass.getParent());
        }

        courseClassMapper.insert(data);

        return Result.success(data.getId());
    }

    /**
     * 获取所有的课程分类
     * @return
     */
    @Override
    public Result<List<Map<String,Object>>> getAll() {
        QueryWrapper<CourseClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del",0);
        List<CourseClass> courseClasses = courseClassMapper.selectList(queryWrapper);
        List<CourseClass> courseClassCollect = courseClasses.stream().filter(data -> data.getParent() == 0)
                                        .collect(Collectors.toList());
        List<Map<String,Object>> res = new ArrayList<>();

        courseClassCollect.forEach(item ->{
            Map<String, Object> map = new HashMap<>();
            map.put("value",item.getName());
            map.put("id",item.getId());
            List<CourseClassVO> courseClassVOS = courseClasses.stream()
                    .filter(data -> data.getParent() == item.getId())
                    .map(data -> new CourseClassVO(data.getName(),data.getId()))
                    .collect(Collectors.toList());
            map.put("children",courseClassVOS);
            res.add(map);
        });

        log.info("当前查询到的课程分类数据为: {}",res);

        return Result.success(res);
    }
}
